#include "preHeader.h"
#include "Session/GameSession.h"
#include "Session/GameSessionHandler.h"
#include "SQLHelper.h"

int GameSessionHandler::HandleLoadAllInstCfgData(GameSession *pSession, INetPacket &pck, const RPCActor::RequestMetaInfo &info)
{
	auto LoadAllInstCfgData = [GSRPCAsyncTaskArgs]() {
		AutoFeedbackLarge(buffer, error)
		auto connPtr = sMysqlDatabasePool.GetCharDB()->GetConnAutoPtr();
		if (!connPtr) {
			error = DBPErrorConnectMysqlFailed;
			return;
		}
		auto rst = connPtr->QueryFormat(
			"SELECT * FROM `%s`", GetTableName<inst_configure>());
		if (!rst) {
			error = DBPErrorQueryMysqlFailed;
			return;
		}
		while (rst.NextRow()) {
			auto row = rst.Fetch();
			auto instInfo = LoadEntityFromMysqlRow<inst_configure>(row);
			SaveToINetStream(instInfo, buffer);
		}
	};
	sAsyncTaskMgr.AddTask(CreateAsyncTask(LoadAllInstCfgData));
	return SessionHandleCapture;
}

int GameSessionHandler::HandleSaveInstCfgData(GameSession *pSession, INetPacket &pck, const RPCActor::RequestMetaInfo &info)
{
	auto SaveInstCfgData = [GSRPCAsyncTaskArgs]() {
		static const std::vector<ssize_t> ingores =
			ConvertEntityFieldIndexs<inst_configure>({"cfgID"});
		inst_configure instInfo;
		LoadFromINetStream(instInfo, *pckPtr);
		AutoFeedback(buffer, error)
		auto connPtr = sMysqlDatabasePool.GetCharDB()->GetConnAutoPtr();
		if (!connPtr) {
			error = DBPErrorConnectMysqlFailed;
			return;
		}
		auto sqlStr = CreateSQL4UpdateEntity(instInfo, "cfgID=%u", ingores);
		auto rst = connPtr->ExecuteFormat(sqlStr.c_str(), instInfo.cfgID);
		if (!rst.second) {
			error = DBPErrorUpdateMysqlFailed;
			return;
		}
	};
	sAsyncTaskMgr.AddTask(CreateAsyncTask(SaveInstCfgData));
	return SessionHandleCapture;
}
